require(['init'], function () {
    //公司的初始密码
    var needPw = true;
    var $name = $('[name=name]');
    var $tuid = $('[name=tuid]');
    var $genderWrap = $('.genderWrap');
    var $courseType = $('#J_coursetypes');
    var $phone = $('[name=phone]');
    var $classInNo = $('[name=classin_no]');
    var $photo = $('#J_img');
    var $resume = $('#J_resume_filename');
    var $email = $('[name=email]');
    var $introduce = $('[name=introduce]');
    var $studentMax = $('[name="teach_student_count"]');
    var $lessontime = $('[name="lessontime_text"]');
    var $submitBtn = $('#J_teacheradd');
    var $imgUpload = $('#J_imgupload');
    var $resumeUpload = $('#J_resume');
    var $education = $('#J_eduction');
    var $workExp = $('#J_workexp');
    var tuid = location.search.urlToObj().tuid;
    var doctorId;
    var teacheruid;
    $('#J_teacheradd').val(i18next.t('personSave.save'))
    ajaxMethod({
        url: ' /api/user/current',
        success: function (data) {
            doctorId = data.userid;
            console.log(data)
            ajaxMethod({
                url: '/api/teacher/user/' + doctorId,
                success: function (data) {
                    console.log(data);
                    teacheruid = data.teacheruid;
                    bind(data)
                }
            });
        }
    });


    function bind(data) {
        console.log(data)
        $name.val(data.lastname);
        $genderWrap.find('input[value="' + data.sex + '"]').click()
        $phone.val(data.mobile);
        $classInNo.val(data.ClassInNo);
        $genderWrap.find('input').attr('disabled',true);
        $.each(data.coursedesc, function (i, item){
            $courseType.find('input[value="' + item + '"]').click()
        });
        $photo.attr('src', data.photo);
        $email.val(data.email);
        $introduce.val(data.introduce);
        $studentMax.val(data.remark1);
        $lessontime.val(data.remark2);
        eduExpTool = new ExperienceTool({
            tips: '请输入就读学校和学历,如 某某大学（本科）',
            data: data.educations
        });
        $('#J_eduction2').append(eduExpTool.$dom);

        workExpTool = new ExperienceTool({
            tips: '请输入工作单位',
            data: data.experiences
        });
        $('#J_workexp2').append(workExpTool.$dom);
    }
    var oSpan = $('.email');
    oSpan.css('color','#d85030');
    $email.on('focus',function () {
        var val = this.value;
        oSpan.text('');
    });
    $email.on('blur', function () {
        var val = this.value;
        var reg =/^[\w\.\-]+@[\w-]+\.[\w-]+$/;
        if(reg.test(val)){

        }else{
            oSpan.text('邮箱格式不正确') ;
        }
        if(val==''){
            oSpan.text('') ;
        }
    });
    if (tuid) {
        $submitBtn.val('保 存');
        $('#resetpassword').show();
        $('#classIntest').hide();
        $classInNo.attr("readonly","readonly")
        $('.breadcrumb .active a').text('编辑教师').attr('href', 'javascript:void(0)')
    }
    function getFileNameByPath(src) {
        return src.replace(/^.+\/([^\/]+)$/, function() {
            if(arguments[1]) {
                return arguments[1]
            }
            return ''
        });
    }

    function loadCourseTypes(callback) {
        ajaxMethod({
            url: '/api/coursetypes',
            success: function (data) {
                $.each(data, function (i, item) {
                    var checkItem = '<span class="check-item" style="margin-right: 0">\
            <span class="icon icon-size-16 icon-checkbox" data-type="checkbox">\
              <input type="checkbox" name="coursetype" value="'+ item.coursetypeuid +'">\
            </span><span data-type="label">'+ item.coursetypename +'</span>\
          </span>&nbsp;';
                      $('#J_coursetypes').append(checkItem);
                });

                callback && callback();
            }
        })
    }

    function imgUpload($container) {
        var $uploadCoverBox = $container.find('.icon-uploadimg')
        var $uploadCoverThumb = $uploadCoverBox.find('img')
        var $uploadInput = $uploadCoverBox.find('input')

        var coverUploadInput = new UploadInput({
            $dom: $uploadInput,
            done: function (uploadImgSrc) {
                console.log(uploadImgSrc);
                var uploadImgFullSrc='/api/file?u=' + uploadImgSrc;

                if (uploadImgSrc) {
                    new ImgCropTool({
                        imgSrc: uploadImgFullSrc,
                        cropSize:[200, 200, 'courseCover'],
                        allowResize: false,
                        success:function(imgSrc){
                            var imgCropSrc = '/api/file?u=' + imgSrc;
                            $uploadCoverBox.attr('data-value', imgCropSrc);
                            $uploadCoverThumb.attr('src', imgCropSrc);
                        }
                    })
                    //TODO
                    /*new ImgCropTool({
                     imgSrc: uploadImgSrc,
                     cropSize: [200, 200],
                     success: function (imgSrc) {
                     $uploadCoverThumb.attr('src', imgSrc);
                     $uploadCoverBox.attr('data-value', uploadImgSrc);
                     }
                     })*/
                }
            }
        });
    }

    function resumeUpload($container) {
        var $uploadCoverBox = $container.find('.icon-upload')
        var $uploadCoverThumb = $uploadCoverBox.find('.J_resume_filename')
        var $uploadInput = $uploadCoverBox.find('input')

        var coverUploadInput = new UploadInput({
            $dom: $uploadInput,
            done: function (uploadSrc) {
                console.log(uploadSrc);
                var uploadFullSrc='/api/file?u=' + uploadSrc;
                var parseSrc = getFileNameByPath(uploadSrc);

                if (uploadSrc) {
                    $uploadCoverBox.hide();
                    $('#J_resume_filename').attr('href', uploadFullSrc).text(parseSrc).css('text-decaration', 'underline');
                    $('.J_file_wrap').show()
                    return;
                }
            }
        });
    }

    function ExperienceTool(options) {

        function ExpItem(options) {
            options = options || {};
            this.tips = options.tips || '请输入';
            this.data = options.data ||  {};
            this.$dom = $('<div style="width: 920px;margin-bottom:15px;"></div>');

            this.yearMonthInputStart = new YearMonthInput(); //
            this.yearMonthInputEnd = new YearMonthInput(); //

            this.$dom.append(this.yearMonthInputStart.$dom);
            this.$dom.append(' ~ ');
            this.$dom.append(this.yearMonthInputEnd.$dom);
            this.$dom.append('<span>&nbsp;&nbsp;&nbsp;&nbsp;</span>')

            this.$textInput = $('<input type="text" class="form-control J_text" style="width:500px;" placeholder="'+ options.tips +'" />').appendTo(this.$dom) //

            this.$rightbtn = $('<span class="icon icon-size-16 icon-plus-square" style="margin-left:15px;"></span>').appendTo(this.$dom);
            this.$rightbtn.on('click', function () {
                var $this = $(this);
                if($this.hasClass('icon-plus-square')) {
                    var expItem = new ExpItem({tips: options.tips});
                    expItem.$rightbtn.removeClass('icon-plus-square').addClass('icon-less-square');
                    $this.parent().after(expItem.$dom);
                } else {
                    var index = $this.parent().index();
                    $this.parent().remove();
                }
            })

            if(this.data) {
                this.yearMonthInputStart.value(+new Date(this.data.begindate));
                this.yearMonthInputEnd.value(+new Date(this.data.enddate));
                this.$textInput.val(this.data.remark);
            }
        }

        function ExperienceList(options) {
            options = options || {};

            this.$dom = $('<div></div>');
            this.data = options.data ;
            this.tips = options.tips || '请输入';
            this.instanceList = [];

            if(this.data && this.data.length) {
                this.init();
            } else {
                this.addItem();
            }
        }

        ExperienceList.prototype = {
            constructor: ExperienceTool,
            addItem: function (data) {
                var expItem = new ExpItem({
                    tips: this.tips,
                    data: data
                })
                if(this.$dom.children().length > 0) {
                    expItem.$rightbtn.removeClass('icon-plus-square').addClass('icon-less-square');
                }
                this.$dom.append(expItem.$dom)
            },
            init: function () {
                var _this = this;
                $.each(this.data, function (i, item) {
                    _this.addItem(item);
                })
            },
            getValue: function () {
                var _this = this;
                this.data = []
                this.$dom.children().each(function (i, item) {
                    var $item = $(item);
                    var $timeInputStart = $($item.find('[data-type="timeinput"]')[0]);
                    var $timeInputEnd = $($item.find('[data-type="timeinput"]')[1]);

                    var yearStart = $timeInputStart.find('.selectInput')[0].value;
                    var monthStart = $timeInputStart.find('.selectInput')[1].value;

                    var yearEnd = $timeInputEnd.find('.selectInput')[0].value;
                    var monthEnd = $timeInputEnd.find('.selectInput')[1].value;

                    var text = $.trim($item.find('.J_text').val())
                    if(yearStart == "" || monthStart == "" || yearEnd == "" || monthEnd == "" || text == "") {
                        return true;
                    }

                    _this.data.push({
                        startTime: new Date(yearStart, monthStart-1).getTime(),
                        endTime: new Date(yearEnd, monthEnd-1).getTime(),
                        text: text
                    })
                })

                return this.data;
            }
        }

        this.expTool = new ExperienceList(options);
        this.$dom = this.expTool.$dom;

    }

    var eduExpTool;
    var workExpTool;
    function loadTeacherData(teacheruid, callback) {
        ajaxMethod({
            url: '/api/teacher/' + teacheruid,
            success: function (data) {
                $name.val(data.lastname).attr('disabled', 'disabled');
                $genderWrap.find('input[value="' + data.sex + '"]').click()
                $phone.val(data.mobile);
                $classInNo.val(data.ClassInNo);

                $.each(data.coursedesc, function (i, item) {
                    $courseType.find('input[value="' + item + '"]').click()
                });

                $photo.attr('src', data.photo);
                $email.val(data.email);
                $introduce.val(data.introduce);
                $studentMax.val(data.remark1);
                $lessontime.val(data.remark2);

                if(data.resume) {
                    $('.icon-upload').hide();
                    $('.J_file_wrap').show().find('a').attr('href', data.resume).text(getFileNameByPath(data.resume)).css('text-decoration', 'underline');
                }


                $resume.attr('href', data.resume);

                eduExpTool = new ExperienceTool({
                    tips: '请输入就读学校和学历,如 某某大学（本科）',
                    data: data.educations
                });
                //$education.append(eduExpTool.$dom);

                workExpTool = new ExperienceTool({
                    tips: '请输入工作单位',
                    data: data.experiences
                });
                // $workExp.append(workExpTool.$dom);

                $('[name=tuid]').val(data.teacheruid);
                (typeof callback == 'function') && callback()
            }
        })
    }

    function submitTeacherData() {
        if(oSpan.text()!=''){
            return
        }
        var sex = $('[name="gender"]:checked').val()
        if (sex == undefined) {
            var checkResult = {
                followTips: true,
                result: '请选择性别',
                status: false
            }
            FormCheck.checkTips($('.J_gender_help'), checkResult);
        }

        var courseId = $('[name="coursetype"]:checked').val();
        // if(courseId == undefined) {
        //   var checkResult = {
        //     followTips: true,
        //     result: '请选择教授课程',
        //     status: false
        //   }
        //   FormCheck.checkTips($('.J_coursetype_help'), checkResult);
        // }

        if (FormCheck.childrenInputCheck($('#J_teacheradd_wrap'))) {
            var name = $name.val()
            var phone = $phone.val()
            var classInNo = $classInNo.val()
            var courseIdArr = [];
            $('[name="coursetype"]:checked').each(function (i, item) {
                courseIdArr.push(item.value)
            })

            var photo = $('#J_uploadCover img').attr('src') || '';
            var email = $email.val()
            var password=$('[name="pw"]').val()
            var introduce = $introduce.val()
            var remark1 = $studentMax.val()
            var remark2 = $lessontime.val()
            var resume = $resume.attr('href')

            var educationValueArr = eduExpTool.expTool.getValue();
            var workValueArr = workExpTool.expTool.getValue();

            var educationPostArr = []
            $.each(educationValueArr, function (i, item) {
                educationPostArr.push({
                    begindate: new Date(item.startTime).Format('YYYY-MM-DD'),
                    enddate: new Date(item.endTime).Format('YYYY-MM-DD'),
                    remark: item.text
                })
            })

            var workPostArr = []
            $.each(workValueArr, function (i, item) {
                workPostArr.push({
                    begindate: new Date(item.startTime).Format('YYYY-MM-DD'),
                    enddate: new Date(item.endTime).Format('YYYY-MM-DD'),
                    remark: item.text
                })
            })

            var postData = {
                lastname: name,
                sex: sex,
                mobile: phone,
                ClassInNo: classInNo,
                coursedesc: courseIdArr,
                photo: photo,
                resume: resume,
                email: email,
                introduce: introduce,
                remark1: remark1,
                remark2: remark2,
                educations: educationPostArr,
                //password:password,
                experiences: workPostArr

            }

            function gotoTeacherList() {
                //location.href = 'personInfo.html';
                var saveSuccess =i18next.t('personSave.savesuccessfully')
                _Tips(saveSuccess)
            }
            // 只修改id=3;
            ajaxMethod({
                url: '/api/teacher/' + teacheruid,
                method: 'put',
                data: $.extend({},postData, { teacheruid: teacheruid }),
                success: function (data) {
                    // $submitBtn.prop('disabled', false);
                    gotoTeacherList();
                }
            })
            // $submitBtn.prop('disabled', true);
            if (teacheruid != undefined) {
                /*ajaxMethod({
                    url: '/api/teacher/' + teacheruid,
                    method: 'put',
                    data: $.extend({},postData, { teacheruid: teacheruid }),
                    success: function (data) {
                        // $submitBtn.prop('disabled', false);
                        gotoTeacherList();
                    }
                })*/


            } else {

                if(needPw=false){
                    ajaxMethod({
                        url: '/api/teacher',
                        method: 'post',
                        data: postData,
                        success: function (data) {
                            // $submitBtn.prop('disabled', false);
                            gotoTeacherList();
                        }
                    })
                }else{
                    ajaxMethod({
                        url: '/api/teacher',
                        method: 'post',
                        data: $.extend({}, postData, {password: password}),
                        success: function (data) {
                            // $submitBtn.prop('disabled', false);
                            gotoTeacherList();
                        }
                    })
                }

            }

        }
    }
    //检测
    var registerDefaultPwd="";
    ajaxMethod({
        url: '/api/organization/1',
        type: 'get',
        success:function(data){
            registerDefaultPwd=data.registerDefaultPwd;
        }
    })
    $('[name="classin_no"]').on('blur',function(){
        classIntest(true);
    })
    var classin_nov="";
    function  classIntest(cl){
        classin_nov=$('[name="classin_no"]').val();
        ajaxMethod({
            url: '/api/eeo/check',
            method: 'post',
            data: {account:classin_nov},
            success: function (data) {
                if(data=="true"){
                    $('.pw').hide();
                    $('#prompt').show();
                    $('#noprompt').hide();
                    $("#resetpassword").attr("disabled",false);
                    needPw=false;
                }else if(data=="fasle"||$('input[name="classin_no"]').val()!=""){
                    $('.pw').show();
                    $('#noprompt').show();
                    $('[name="pw"]').val(registerDefaultPwd);
                    $('#prompt').hide();
                    needPw=true;
                    $("#resetpassword").attr("disabled",true);
                }
            }

        })
    }
    $('[name="pw"]').on('blur',function(){
        if($('[name="pw"]').val()!=""){
            $('#prompt').hide();
            $('#noprompt').hide();
        }else{
            $('#noprompt').show();
        }
    })
    //重置密码
    var account="";
    $("#resetpassword").on('click',function(){
        account=$('[name="classin_no"]').val();
        //console.log(account)
        reset()
    })
    function reset(){
        var $ClassInDom=$('<div class="formList" id="J_teacheradd_wrap" style="margin-top:12px;">\
          <div class="formLi" >\
            <div class="formLi" >\
              <div class="formTitle required">\
                  <span>新&nbsp&nbsp&nbsp密&nbsp&nbsp&nbsp码</span>\
              </div>\
              <div class="formContent">\
                  <input class="form-control" data-formcheck="length" type="text"  name="passwordnew" style="width:226px;">\
              </div>\
          </div>\
          <div class="formLi" >\
              <div class="formTitle required">\
                  <span>确认新密码</span>\
              </div>\
              <div class="formContent">\
                  <input class="form-control" data-formcheck="length" type="text"  name="passwordold" style="width:226px;">\
                  <p style="color:red;display:none;margin-top:30px;" class="p">两次输入密码不一致</p>\
              </div>\
            </div>\
          </div>');
        var popUpBox = new PopUpBox({
            type: 'dom',
            style: 'default contentScroll',
            //submitBtnType:false,
            submitBtnType:'alert',
            titleText: '请输入要设置的密码',
            show: true,
            content: $ClassInDom,
            callback: {
                yes: function (e) {
                    var passwordold=$ClassInDom.find('[name="passwordold"]').val();
                    var passwordnew=$ClassInDom.find('[name="passwordnew"]').val();
                    if(passwordold!=""||passwordnew!=""){
                        if(passwordold!=passwordnew){
                            $('.p').show();
                            return false;
                        }else{
                            $('.p').hide();
                            ajaxMethod({
                                url: '/api/eeo/reset',
                                method: 'post',
                                data: {account:account,
                                    password:passwordold
                                },
                                success: function (data) {
                                    //console.log(data);
                                }
                            })
                        }
                    }else{
                        return false;
                    }

                }
            },
            position: {
                width: 423,
                height:304,
            }
        })
        popUpBox.submitBtnBox.$dom.css('text-align', 'right')
    }

    function bindSubmit() {
        $submitBtn.on('click', submitTeacherData)
        $('body').on('click', '#J_resume .icon-delete', function () {
            var _this = this;
            var returnVal = confirm('确定删除该简历?')
            if(returnVal) {
                ajaxMethod({
                    url: '/api/teacher/'+ tuid +'/resume',
                    method: 'delete',
                    success: function (data, status) {
                        if(status.code == 0) {
                            $(_this).parent().hide().next().show();
                        }
                    }
                })
            }
        })
    }

    imgUpload($imgUpload);
    resumeUpload($resumeUpload);

    // //同步手机号到classInNo,只同步一次
    // $phone.on('blur', function () {
    //   if(FormCheck.inputCheck($(this), true).status) {
    //       if(!$classInNo.val()) {
    //         $classInNo.val($(this).val())
    //       }
    //   }
    // })
    bindSubmit();

    if(tuid) {
        //编辑
        loadCourseTypes(function () {
            loadTeacherData(tuid);
        });
    } else {
        //创建
        loadCourseTypes();
        var eduExpTool = new ExperienceTool({tips: '请输入就读学校和学历,如 某某大学（本科）'});
        $education.append(eduExpTool.$dom);

        var workExpTool = new ExperienceTool({tips: '请输入工作单位'});
        $workExp.append(workExpTool.$dom);
    }

})
